﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Kristall.Screens;
using System.IO;

namespace Kristall.Editor
{
    public partial class DictionaryEditor : Form
    {
        Dictionary<string, AnimatableSprite> _dictionary;
        private LevelEditor _levelEditor;

        public DictionaryEditor(Dictionary<string, AnimatableSprite> dictionary, LevelEditor levelEditor)
        {
            InitializeComponent();

            _dictionary = dictionary;
            _levelEditor = levelEditor;

            loadSpriteDialog.InitialDirectory = AnimatableSprite.FullSpritesPath;

            updateKeys();
        }


        private void keys_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(keys.SelectedItem != null)
            {
                propertyGrid1.SelectedObject = _dictionary[(string)keys.SelectedItem];
            }
        }

        void updateKeys()
        {
            keys.Items.Clear();
            _dictionary.Keys.ToList().ForEach(x => keys.Items.Add(x));
        }

        void addAnimatable(string fileName)
        {
            AnimatableSprite animation = AnimatableSprite.LoadForEditor(fileName, _levelEditor.Level.SpriteTextures, _levelEditor.Content);
            string key = Path.GetFileName(fileName);
            _dictionary.Add(key, animation);

            updateKeys();
        }


        private void add_Click(object sender, EventArgs e)
        {
            if (loadSpriteDialog.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < loadSpriteDialog.FileNames.Length; i++)
                {
                    string fileName = loadSpriteDialog.FileNames[i];
                    //Make sure that the selected image is located in a subdir of \Content
                    if (fileName.StartsWith(Kristall.FullContentPath))
                    {
                        addAnimatable(fileName);
                    }
                    else
                    {
                        MessageBox.Show("Please choose a sprite that is located in or a subdir of the Content folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void remove_Click(object sender, EventArgs e)
        {
            if (keys.SelectedItem != null)
            {
                _dictionary.Remove((string)keys.SelectedItem);

                updateKeys();
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
